179. 最大数
为保证权益,题目请参考 179. 最大数(From LeetCode).
解决方案1
CPP
C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool cmp2(const string &as, const string &bs, const int i = 0)
{
if (as.length() <= i)
{
if (bs[i] == bs[0])
{
return cmp2(bs.substr(1), bs.substr(i + 1) + as);
}
else
{
return bs[i] < bs[0];
}
}
if (bs.length() <= i)
{
if (as[i] == as[0])
{
return cmp2(as.substr(i + 1) + bs, as.substr(1));
}
else
{
return as[i] > as[0];
}
}
if (as[i] == bs[i])
{
return cmp2(as, bs, i + 1);
}
else
{
return as[i] > bs[i];
}
};
bool cmp(int a, int b)
{
const string as = to_string(a);
const string bs = to_string(b);
return cmp2(as, bs);
}
class Solution
{
public:
string largestNumber(vector<int> &nums)
{
sort(nums.begin(), nums.end(), cmp);
string ans = "";
for (int x : nums)
{
ans += to_string(x);
}
if (ans[0] == '0')
{
return "0";
}
else
{
return ans;
}
}
};
int main()
{
Solution so;
vector<int> vec;
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
vec.push_back(0);
cout << so.largestNumber(vec) << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102